
//set correct package for your app
package com.eclecticconceptions.vulcan;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.widget.Toast;

import com.google.android.vending.licensing.AESObfuscator;
import com.google.android.vending.licensing.LicenseChecker;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.ServerManagedPolicy;



/**
 * NOTES ON USING THIS LICENSE FILE IN YOUR APPLICATION: 
 * 1. Define the package
 * of you application above 
 * 2. Be sure your public key is set properly  @BASE64_PUBLIC_KEY
 * 3. Change your SALT using random digits 
 * 4. Under AllowAccess, Add your previously used MainActivity 
 * 5. Add this activity to
 * your manifest and set intent filters to MAIN and LAUNCHER 
 * 6. Remove Intent Filters from previous main activity
 * 7. Set up RETRY action if required dontAllow code 291
 * Note NOT_LICENSED code is 561
 * 
 */
public class LicenseCheck extends Activity {
	public static final long RECHECK_PERIOD = 604800000L;  //7days - duration in milliseconds between checks; info: 86,400,000 milliseconds in a day
	public static final int REVIEW_DELAY = 7; //number of times app is opened before prompting user to write review
	
	public static final int NO_LICENSE_DIALOG_ID = 0;
	public static final int REVIEW_REQUEST_DIALOG_ID = 1;
	
	private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmFn9frYcejPdwGpvjShCGCDVJVUSXCjb/sVaTRG8wzIHhIN6VbMwDUOUzqi768tjzlk7Wo3SqIGj+NvWeSN5OFLOPauqGIkHPjzPKZXq9dnPJqEhOjI0GVblXW0y8f3ATWym8Pb0ONYsGUxS+cHVVUsvqp+mLJ6iJKmuervhxrG6TvZQWZEi5YU+O0x9OvCzrlCSiwmOeKBlULOGyggD9BiX2tqfidw6dBUoH7lq5dvPXAbYJzNrIHZnw/aMvd3uUelttIAPGoGA7RoF0v8iwQKMgyDXUDNH28/PEAsPfENDoLF+antExNWi1V0gaT5eQstBO/OmDS/L/u2jrMOmLwIDAQAB";
	
	private static final byte[] SALT = new byte[] { 10,76,-97,65,38,-23,14,-81,-26,76,45,32,-92,14,-84,-49,-51,123,88,-20 };
	
	// A handler on the UI thread.
	private Handler mHandler;
	
	private LicenseChecker mChecker;
	private LicenseCheckerCallback mLicenseCheckerCallback;
	private Toast mToast;
	private Long lastTimeLicenseConfirmed;
	private int timesAppOpened;
	private SharedPreferences mSettings;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		
		mHandler=new Handler();
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); 
		//check if license previously confirmed - LicenseOK - retrieve datestamp if ok
		mSettings = getSharedPreferences(Cp12Utils.PREFS_FILE, 0);
		lastTimeLicenseConfirmed = mSettings.getLong("lastTimeLicenseConfirmed", 0L);
		timesAppOpened=mSettings.getInt("timesAppOpened",0);
		//if so and within recheck period? launch main activity
		
		// Try to use more data here. ANDROID_ID is a single point of attack.
		String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		// Library calls this when it's done.
		mLicenseCheckerCallback = new MyLicenseCheckerCallback();
		// Construct the LicenseChecker with a policy.
		mChecker = new LicenseChecker(this, new ServerManagedPolicy(this,
						new AESObfuscator(SALT, getPackageName(), deviceId)),
						BASE64_PUBLIC_KEY);
		
	
		if (lastTimeLicenseConfirmed + RECHECK_PERIOD > System.currentTimeMillis()){
			//Toast.makeText(this, "No Check Required", Toast.LENGTH_SHORT); 
			startMainActivity();
			
		} else {
			//toast("Check License");
		//if not check the license
		//if license ok then set pref LicenseOK to datestamp of now
		doCheck();
		}
	}
	
	public void toast(final String string) {
		mHandler.post(new Runnable() { 
            public void run() { 
            	mToast.setText(string);
            	mToast.show();
            } 
        }); 
		
	}
	
	private class MyLicenseCheckerCallback implements LicenseCheckerCallback {

		public void allow(int reason) {
			if (isFinishing()) {
				// Don't update UI if Activity is finishing.
				return;
			}
			//set last time license confirmed in shared preferences, so it will not be rechecked untill recheck period expired
			
			SharedPreferences.Editor editor = mSettings.edit();
		      editor.putLong("lastTimeLicenseConfirmed", System.currentTimeMillis());
		      // Commit the edits!
		      editor.commit();
			// Allow user access.
		      //toast("Allow: "+ reason);
			startMainActivity();

		}//allow

		public void applicationError(int errorCode) {
			
			if (isFinishing()) {
				// Don't update UI if Activity is finishing.
				return;
			}
			// This is a polite way of saying the developer made a mistake
			// while setting up or calling the license checker library.
			// Please examine the error code and fix the error.
			/*String mErrorString = "";
			switch(errorCode){
			case ERROR_CHECK_IN_PROGRESS:
				mErrorString="ERROR_MISSING_PERMISSION";
				break;
			case ERROR_INVALID_PACKAGE_NAME:
				mErrorString="ERROR_INVALID_PACKAGE_NAME";
				break;
			case ERROR_INVALID_PUBLIC_KEY:
				mErrorString="ERROR_INVALID_PUBLIC_KEY";
				break;
			case ERROR_MISSING_PERMISSION:
				mErrorString="ERROR_MISSING_PERMISSION";
				break;
			case ERROR_NON_MATCHING_UID:
				mErrorString="ERROR_NON_MATCHING_UID";
				break;
			case ERROR_NOT_MARKET_MANAGED:
				mErrorString="ERROR_NOT_MARKET_MANAGED";
				break;
			}
			toast("Error: " + errorCode + " : " + mErrorString);
			*/
			startMainActivity();

		}  //apperror

		public void dontAllow(int reason) {
			// Should not allow access. In most cases, the app should assume
						// the user has access unless it encounters this. If it does,
						// the app should inform the user of their unlicensed ways
						// and then either shut down the app or limit the user to a
						// restricted set of features.
						// In this example, we show a dialog that takes the user to Market.
			if (isFinishing()) {
				// Don't update UI if Activity is finishing.
				return;
			}
			if (reason==291){
				//toast("dontAllow: "+ reason);
				startMainActivity();
				return;
			}
			//toast("Error: " + errorCode + " : " + mErrorString);
			//if license check failed then set checktime to 0 so app rechecks next time it is opened
			SharedPreferences.Editor editor = mSettings.edit();
		      editor.putLong("lastTimeLicenseConfirmed", 0);
		      // Commit the edits!
		      editor.commit();
			//toast("dontAllow: "+ reason);
			showDialog(NO_LICENSE_DIALOG_ID);
		}
	
	}	

	private void doCheck() {

		mChecker.checkAccess(mLicenseCheckerCallback);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// 
		Dialog dialog;
		
		switch(id) {
		
		case NO_LICENSE_DIALOG_ID:
		return new AlertDialog.Builder(this)
				.setTitle("Application License Incorrect")
				.setCancelable(false)
				.setMessage(
						"This application is not properly licensed. Please purchase it from Google Play.")
				.setPositiveButton("Google Play",
						new DialogInterface.OnClickListener() {
							//@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent marketIntent = new Intent(
										Intent.ACTION_VIEW,
										Uri.parse("http://market.android.com/details?id="
												+ getPackageName()));
								startActivity(marketIntent);
								finish();
							}
						})
				.setNegativeButton("Exit",
						new DialogInterface.OnClickListener() {
							//@Override
							public void onClick(DialogInterface dialog,int which) {
								finish();
							}
						}).create();
			
		case REVIEW_REQUEST_DIALOG_ID:
			return new AlertDialog.Builder(this)
			.setTitle("Review Request")
			.setCancelable(false)
			.setMessage(
					"If you are pleased with this App, we would be VERY grateful if you could review it on Google Play." +
					"Many Thanks, we will not bother you again.")
			.setPositiveButton("Review Now",
					new DialogInterface.OnClickListener() {
						//@Override
						public void onClick(DialogInterface dialog,
								int which) {
							Intent marketIntent = new Intent(
									Intent.ACTION_VIEW,
									Uri.parse("http://market.android.com/details?id="
											+ getPackageName()));
							startActivity(marketIntent);
							finish();
						}
					})
			.setNegativeButton("No Thanks",
					new DialogInterface.OnClickListener() {
						//@Override
						public void onClick(DialogInterface dialog,int which) {
							dialog.cancel();
						}
					}).create();
		
		default:
			dialog=null;
				
		}//end switch
		
		return dialog;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mChecker.onDestroy();
		
	}

	private void startMainActivity() {
		//get times_app_opened from shared prefs
				//increase times_app_opened by 1;		
				//if app has been opened REVIEW_DELAY times then open dialog for leaving review
				// if cancel pressed continue, if ok pressed
				//increase times_app_opened by 1
		timesAppOpened++;
		SharedPreferences.Editor editor = mSettings.edit();
		editor.putInt("timesAppOpened", timesAppOpened);
	    // Commit the edits!
	    editor.commit();
	    
		//REPLACE MainActivity.class WITH YOUR APPS ORIGINAL LAUNCH ACTIVITY
		startActivity(new Intent(this, Cp12Activity.class)); 
		finish();
	}

	

}